<script setup lang="ts">
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import {
  categoryListRequest,
  addAttrRequest,
  attrListRequest,
  attrUpdateRequest,
  attrDeleteRequest,
} from '@/api/attr'
import type { Category, AttrVo, AttrValueSelect, AttrValue } from '@/api/attr/type'
import type { FormInstance, FormRules } from 'element-plus'
import { toRaw } from 'vue'
// 一级分类
const categoryLevelOneVos = ref<Category[]>()
// 二级分类
const categoryLevelTwoVos = ref<Category[]>()
// 三级分类
const categoryLevelThreeVos = ref<Category[]>()
// 一级分类下拉项绑定值
const categoryLevelOneID = ref<number>()
// 二级分类下拉项绑定值
const categoryLevelTwoID = ref<number | undefined>()
// 三级分类下拉项绑定值
const categoryLevelThreeID = ref<number>()
// 属性集合
const attrValueSelectList = ref<AttrValueSelect[]>([])
onMounted(async () => {
  await categoryListRequest(0)
    .then((res) => {
      categoryLevelOneVos.value = res
    })
    .catch((err) => console.log(err))
})
// 属性值
const attrValueSelect = reactive<AttrValueSelect>({ attrID: 0, attrName: '', attrValues: [] })
// 分类下拉项选中值发生变化时触发，查询子分类信息
const change = async (data: number) => {
  let parentCID = 0
  switch (data) {
    case 1:
      parentCID = categoryLevelOneID.value as number
      categoryLevelTwoID.value = undefined
      categoryLevelThreeID.value = undefined
      // 清空数据
      clearData()
      break
    case 2:
      parentCID = categoryLevelTwoID.value as number
      categoryLevelThreeID.value = undefined
      // 清空数据
      clearData()
      break
    case 3:
      parentCID = categoryLevelThreeID.value as number
      // 清空数据
      clearData()
  }
  // 判断分类信息的等级
  await categoryListRequest(parentCID)
    .then(async (res) => {
      switch (data) {
        case 1:
          categoryLevelTwoVos.value = res
          break
        case 2:
          categoryLevelThreeVos.value = res
          break
        case 3:
          await queryAttrList()
          // 隐藏保存窗口，显示查询窗口
          windowVisible.value = !windowVisible.value
      }
    })
    .catch((err) => console.log(err))
}
// 切换【新增及修改属性窗口】和【展示属性窗口】控制符，true-展示属性窗口展示，false-新增及修改属性窗口展示
const windowVisible = ref(true)
// 控制按钮文字：true-添加，false-修改
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let addOrUpdate = true
// 点击新增属性按钮
const addAttrValueSelect = () => {
  addOrUpdate = true
  attrValueSelect.attrValues.push({ attrValue: '' })
}
// 表格索引变量
let attrSelectValueIndex = ref(0)
// 【新增及修改】属性值窗口表格索引
const indexMethod = (index: number) => {
  attrSelectValueIndex.value = index
  return index + 1
}
// 删除属性值按钮单击事件
const deleteAttrValueSelect = (row) => {
  attrValueSelect.attrValues.filter((item) => item.attrValue !== row)
  attrValueSelect.attrValues.splice(attrSelectValueIndex.value, 1)
}
const disable = ref<boolean>(false)
// input框失去焦点事件
const toBlur = (row) => {
  for (let i = 0; i < attrValueSelect.attrValues.length - 1; i++) {
    console.log(row)
    console.log(attrValueSelect.attrValues[i])
    console.log(row === attrValueSelect.attrValues[i])
    if (row.attrValue === attrValueSelect.attrValues[i].attrValue) {
      return (disable.value = true)
    } else {
      return (disable.value = false)
    }
  }
}
// 表单实例
const ruleFormRef = ref<FormInstance>()
// 属性值校验规则
const checkAttrValue = (rule: any, value: AttrValue[], callback: any) => {
  value.forEach((item: AttrValue) => {
    if (item.attrValue === '') {
      callback(new Error('属性值不能为空'))
    } else if (categoryLevelThreeID.value === undefined) {
      callback(new Error('请选择分类信息'))
    }
    callback()
  })
}
// 表单校验规则
const rules = reactive<FormRules<AttrValueSelect>>({
  attrName: [
    { required: true, message: '请输入属性名', trigger: 'change' },
    { min: 2, max: 30, message: '长度在2到30之间' },
  ],
  attrValues: [{ validator: checkAttrValue, trigger: 'blur' }],
})
// 属性vo
const attrVo = ref<AttrVo>({
  attrID: 0,
  attrName: '',
  searchType: false,
  icon: '',
  valueSelect: '',
  attrType: 0,
  enable: false,
  catalogID: 0,
  showDescription: false,
})
// 保存按钮点击回调函数
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      // 校验通过，将查属性值拼接成字符串，存放到vo中
      for (let i = 0; i < attrValueSelect.attrValues.length; i++) {
        if (i < attrValueSelect.attrValues.length - 1) {
          attrVo.value.valueSelect += attrValueSelect.attrValues[i].attrValue + ';'
        } else {
          attrVo.value.valueSelect += attrValueSelect.attrValues[i].attrValue
        }
      }
      attrVo.value.attrName = attrValueSelect.attrName
      attrVo.value.catalogID = categoryLevelThreeID.value as number
      attrVo.value.attrID = attrValueSelect.attrID
      // 若attrID为0，则发送保存请求，否则发送修改请求
      if (attrVo.value.attrID === 0) {
        // 发送保存属性值的请求
        await addAttrRequest(attrVo.value)
          .then(() => {
            queryAttrList()
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        // 发送修改属性请求
        await attrUpdateRequest(attrVo.value)
          .then(() => {
            // 重新查询属性值
            queryAttrList()
          })
          .catch((err) => {
            console.log(err)
          })
      }
    }
  })
}
// 取消保存按单击回调函数
const cancelSave = () => {
  windowVisible.value = !windowVisible.value
}
// 【展示属性】窗口索引
let attVoIndexMethod = (index: number) => {
  return index + 1
}
// 修改属性值按钮点击事件
const updateAttrValues = (row) => {
  addOrUpdate = false
  // 显示【修改窗口】，隐藏【展示窗口】
  windowVisible.value = !windowVisible.value
  Object.assign(attrValueSelect, row)
}
// 重新查询属性信息
const queryAttrList = async () => {
  // 隐藏保存窗口，显示查询窗口
  windowVisible.value = !windowVisible.value
  // 清空数据
  clearData()
  await attrListRequest(categoryLevelThreeID.value as number).then((res: AttrVo[]) => {
    for (let i = 0; i < res.length; i++) {
      attrValueSelectList.value.push({
        attrID: res[i].attrID,
        attrName: '',
        attrValues: [],
      })
      attrValueSelectList.value[i].attrName = res[i].attrName
      res[i].valueSelect.split(';').forEach((attrValue) => {
        attrValueSelectList.value[i].attrValues.push({ attrValue })
      })
    }
  })
}
// 清空数据
const clearData = () => {
  attrValueSelectList.value = []
  attrValueSelect.attrID = 0
  attrValueSelect.attrName = ''
  attrValueSelect.attrValues = []
}
// 删除属性
const deleteAttrVo = async (attrID: number) => {
  await attrDeleteRequest(attrID)
    .then((res) => {
      windowVisible.value = !windowVisible.value
      // 删除成功之后重新查询数据
      queryAttrList()
    })
    .catch((err) => {
      console.log(err)
    })
}
</script>

<template>
  <div class="container">
    <!--  分类卡片-->
    <el-card class="category-card">
      <el-form :inline="true" class="form-inline">
        <el-form-item label="一级分类">
          <el-select clearable v-model="categoryLevelOneID">
            <el-option
              @click="change(1)"
              v-for="categoryVo in categoryLevelOneVos"
              :key="categoryVo.categoryID"
              :label="categoryVo.name"
              :value="categoryVo.categoryID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select clearable v-model="categoryLevelTwoID">
            <el-option
              @click="change(2)"
              v-for="categoryVo in categoryLevelTwoVos"
              :key="categoryVo.categoryID"
              :label="categoryVo.name"
              :value="categoryVo.categoryID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类">
          <el-select clearable v-model="categoryLevelThreeID">
            <el-option
              @click="change(3)"
              v-for="categoryVo in categoryLevelThreeVos"
              :key="categoryVo.categoryID"
              :label="categoryVo.name"
              :value="categoryVo.categoryID"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <!--    属性卡片-->
    <el-card>
      <!--      新增及修改属性按钮-->
      <el-button
        v-show="windowVisible"
        :disabled="!categoryLevelThreeID"
        type="primary"
        :icon="Plus"
        style="margin-bottom: 0.5rem"
        @click="windowVisible = !windowVisible"
      >
        {{ addOrUpdate ? '添加' : '修改' }}平台属性
      </el-button>
      <!--      新增及修改属性窗口-->
      <div v-show="!windowVisible">
        <el-form ref="ruleFormRef" :model="attrValueSelect" :rules="rules">
          <el-form-item label="属性名称" prop="attrName">
            <el-input style="width: 10rem" v-model="attrValueSelect.attrName" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Plus" @click="addAttrValueSelect" :disabled="disable">
              添加属性值
            </el-button>
            <el-button>取消</el-button>
          </el-form-item>
          <el-form-item prop="attrValues">
            <el-table style="width: 100%" border :data="attrValueSelect.attrValues">
              <el-table-column type="selection" align="center" width="81"></el-table-column>
              <el-table-column
                type="index"
                :index="indexMethod"
                label="序号"
                width="120"
                align="center"
              />
              <el-table-column label="属性值" align="center">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.attrValue"
                    placeholder="请输入属性值"
                    @blur="toBlur(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="200">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    alt="删除"
                    @click="deleteAttrValueSelect(scope.row.attrValue)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" @click="submitForm(ruleFormRef)">保存</el-button>
            <el-button size="large" @click="cancelSave">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--      展示属性窗口-->
      <div v-show="windowVisible">
        <el-scrollbar class="el-scrollbar">
          <el-table :data="attrValueSelectList" style="width: 100%" border>
            <el-table-column type="selection" align="center" width="81"></el-table-column>
            <el-table-column
              type="index"
              :index="attVoIndexMethod"
              label="序号"
              width="120"
              align="center"
            />
            <el-table-column prop="attrName" label="属性名称" width="130" align="center" />
            <el-table-column label="属性值" align="left">
              <template #default="scope">
                <span class="attrValue" v-for="item in scope.row.attrValues">
                  {{ item.attrValue }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="260">
              <template #default="scope">
                <el-button
                  type="primary"
                  :icon="Edit"
                  size="small"
                  @click="updateAttrValues(scope.row)"
                />
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon-color="#626AEF"
                  title="确定要删除吗?"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      size="small"
                      :icon="Delete"
                      @click="deleteAttrVo(scope.row.attrID)"
                    />
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.container {
  padding: 1rem;
  width: 100%;

  .category-card {
    padding-left: 0.5rem;

    .form-inline {
      display: flex;

      .el-select {
        --el-select-width: 15rem;
      }
    }
  }
  .el-scrollbar {
    height: calc(100vh - var(--el-scrollbar-height));

    .attrValue {
      background-color: rgb(230 252 31);
      margin-left: 0.5rem;
      padding: 0.5rem;
    }
  }
}
</style>
